/*
 * Clase que alberga los emtodos necesarios para verificar que en cada action se
 * cumplan las directivas de seguridad necesarias.
 */
package Acceso;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;
import org.json.JSONObject;

/**
 *
 * @author alb3rto
 */
public class Security {

    private Security() {
    }

    public Security(HttpServletRequest request, String[] array) {
        validateSession(request, array);
    }

    public static boolean validateSession(HttpServletRequest request, String[] array) {
        try {
            HttpSession sesion = request.getSession(false);
            // obtenemos la sesion
            boolean allow = false;
            ArrayList<String> roles = (ArrayList<String>) sesion.getAttribute("roles");
            List allowed = Arrays.asList(array);
            Iterator it = allowed.iterator();
            while (it.hasNext() && !allow) {
                String rol = (String) it.next();
                allow = (roles != null && roles.contains(rol));
            }
            return allow;
        } catch (IllegalStateException e) {
            return false;
        }
    }

    public static void privilegeError(HttpServletResponse response) {
        JSONObject jo = new JSONObject();
        jo.put("error", 1);
        jo.put("msg", "No cuenta con privilegios para realizar esta accion");

        response.setContentType("text/json");
        try {
            PrintWriter pw = response.getWriter();
            pw.write(jo.toString());
            pw.flush();
            pw.close();
        } catch (IOException ex) {
        }
    }
}
